using Microsoft.EntityFrameworkCore;
using System;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
using Xms.Abp.Data;
using Xms.Abp.Storage;

namespace IdentityManagement
{
    /// <summary>
    /// Base class for the Entity Framework database context used for identity.
    /// </summary>
    [DynamicConnStringName(typeof(IdentityManagementDbProperties), nameof(IdentityManagementDbProperties.ConnStringName))]
    public class IdentityManagementStorage : XmsStorage<IdentityManagementStorage>, IIdentityManagementStorage
    {
        public DbSet<IdentityUser> Users { get; set; }

        public DbSet<IdentityRole> Roles { get; set; }

        public DbSet<IdentityClaimType> ClaimTypes { get; set; }

        public DbSet<OrganizationUnit> OrganizationUnits { get; set; }

        public DbSet<IdentitySecurityLog> SecurityLogs { get; set; }

        public DbSet<IdentityLinkUser> LinkUsers { get; set; }

        public IdentityManagementStorage(DbContextOptions<IdentityManagementStorage> options, IServiceProvider serviceProvider)
            : base(options, serviceProvider)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<IdentityUserRole>(b =>
            {
                b.HasOne<IdentityRole>().WithMany().HasForeignKey(ur => ur.RoleId).IsRequired();
                b.HasOne<IdentityUser>().WithMany(u => u.Roles).HasForeignKey(ur => ur.UserId).IsRequired();
            });

            builder.Entity<OrganizationUnit>(b =>
            {
                b.HasMany<OrganizationUnit>().WithOne().HasForeignKey(ou => ou.ParentId);
            });

            builder.Entity<OrganizationUnitRole>(b =>
            {
                b.HasOne<IdentityRole>().WithMany().HasForeignKey(ou => ou.RoleId).IsRequired();
            });

            builder.Entity<IdentityUserOrganizationUnit>(b =>
            {
                b.HasOne<OrganizationUnit>().WithMany().HasForeignKey(ou => ou.OrganizationUnitId).IsRequired();
            });
        }
    }
}
